import { computed, Ref } from "vue";
import { message as Message } from "ant-design-vue";
import printJs from "print-js";
import { printLabelApi } from "@/api/common";
import CommonHook from "@/hook/commonHook";
export default function LabelHook(state: { loading: Ref<boolean>; tableRef: any }) {
  const { loading, tableRef } = state;

  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { downloadFileByBlob } = CommonHook();

  // 打印
  const printLabelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          const pdfUrl = window.URL.createObjectURL(res.data);
          printJs({ printable: pdfUrl, type: "pdf" });
        }
      })
      .finally(() => (loading.value = false));
  };

  // 下载标签
  const downloadLabelHandle = (buttonType: number | undefined) => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2, buttonType })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          //判断推单状态
          if (res.headers["content-type"] === "application/pdf") {
            const { waybillNum, channelName, itemNumber } = selectRows.value[0];
            downloadFileByBlob(res.data, `${waybillNum}+${itemNumber}件+${channelName}.pdf`, "application/pdf");
          } else {
            downloadFileByBlob(res.data, "标签.zip");
          }
        }
      })
      .finally(() => (loading.value = false));
  };

  return {
    printLabelHandle,
    downloadLabelHandle
  };
}
